package com.simplesoft.accountbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;

public class ExportDatabaseTask extends AsyncTask<Void, Void, Boolean> {
	private BetterProgressDialog progressDlg = null;
	private Context parent = null;
	private final String BACKUP_FILE_NAME = "MoneyRecord.db";
	private final String PACKAGE_NAME = "com.simplesoft.accountbook";
	
	public ExportDatabaseTask (Context parent) {
		this.parent = parent;
	}
	
	@Override
	protected void onPreExecute() {
		this.progressDlg = new BetterProgressDialog(this.parent);
		this.progressDlg.show();
	}

	@Override
	protected Boolean doInBackground(Void... params) {
		if (checkSDCard() != 0) {
			return false;
		}
		
		File fdb = new File(Environment.getDataDirectory().getPath() + "/data/" + PACKAGE_NAME + "/databases/account_book");
		File fbak = new File(Environment.getExternalStorageDirectory(), BACKUP_FILE_NAME);
		FileChannel fcin = null;
		FileChannel fcout = null;
		try {
			fbak.createNewFile();
			fcin = new FileInputStream(fdb).getChannel();
			fcout = new FileOutputStream(fbak).getChannel();
			fcin.transferTo(0, fcin.size(), fcout);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if (fcin != null) {
					fcin.close();
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
			try {
				if (fcout != null) {
					fcout.close();
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		this.progressDlg.dismiss();
		if (result) {
			Toast.makeText(this.parent, parent.getString(R.string.str_successful_db_export), Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this.parent, parent.getString(R.string.str_failed_db_export), Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onProgressUpdate(Void... values) {
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
	}
	
	private int checkSDCard () {
		String state = Environment.getExternalStorageState();
		
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return 0; //SD card is okay.
		} else if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
			return 1; //SD card is read-only.
		} else {
			return 2; //SD card is not available.
		}
	}
}
